from db_base import DatabaseManager, dbconfig


class DoctorManager:
    def __init__(self):
        self.db_manager = DatabaseManager(dbconfig)

    def __del__(self):
        # 确保资源释放
        self.db_manager.close()

    def get_available_therapists(self, doctor_id):
        """
        获取可分配给当前医生的治疗师列表（未分配给该医生的治疗师）
        参数:
            doctor_id: 当前医生ID
        返回:
            list: 可分配治疗师列表，每个治疗师包含id, name, specialty, license_number
            或空列表（出错或无结果）
        """
        try:
            # 使用子查询获取未分配的治疗师
            therapists_query = """
                SELECT user_id, username
                FROM users 
                WHERE role = 'therapist' 
                AND user_id NOT IN (
                    SELECT therapist_id 
                    FROM doctor_therapist_relation 
                    WHERE doctor_id = %s
                )
            """
            return self.db_manager.execute_query(therapists_query, (doctor_id,))
        except Exception as e:
            # 更详细的错误日志记录
            print(f"获取可分配治疗师失败: {e.__class__.__name__}: {e}")
            return []

    def assign_therapist_to_doctor(self, doctor_id, therapist_id):
        """
        将指定的治疗师分配给指定的医生
        参数:
            doctor_id: 当前医生ID
            therapist_id: 要分配的治疗师ID
        返回:
            bool: 分配是否成功
        """
        try:
            # 检查治疗师是否已经分配给该医生
            check_query = """
                SELECT COUNT(*)
                FROM doctor_therapist_relation 
                WHERE doctor_id = %s AND therapist_id = %s
            """
            already_assigned = self.db_manager.execute_query(check_query, (doctor_id, therapist_id))
            if already_assigned[0].get('COUNT(*)', 0) > 0:
                # 如果治疗师已经分配给该医生，则返回 False
                return False
            # 否则，将治疗师分配给医生
            assign_query = """
                INSERT INTO doctor_therapist_relation (doctor_id, therapist_id,created_at)
                VALUES (%s, %s, now())
            """
            self.db_manager.execute_query(assign_query, (doctor_id, therapist_id,),commit=True)
            return True
        except Exception as e:
            # 更详细的错误日志记录
            print(f"分配治疗师失败: {e.__class__.__name__}: {e}")
            return False


    def save_new_patient(self, self1, patient_data):
        pass
